package com.nondo.rdp.finance.service.impl.product;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.product.SecurityOpen;
import com.nondo.rdp.finance.repository.product.SecurityOpenRepository;
import com.nondo.rdp.finance.service.product.SecurityOpenService;

@Transactional
@Service
public class SecurityOpenServiceImpl implements SecurityOpenService {
    @Autowired
    SecurityOpenRepository securityOpenRepository;

    @Override
    public SecurityOpen findOne(Long id) {
        return this.securityOpenRepository.findOne(id);
    }

    @Override
    public SecurityOpen save(SecurityOpen securityOpen) {
        return this.securityOpenRepository.save(securityOpen);
    }

    @Override
    public void update(SecurityOpen securityOpen) {
        this.securityOpenRepository.save(securityOpen);
    }

    @Override
    public void delete(Long id) {
        this.securityOpenRepository.deleteById(id);
    }

    @Override
    public Page<SecurityOpen> findAll(Page<SecurityOpen> page, SecurityOpen securityOpen) {
        Sort sort = new Sort(Sort.Direction.DESC, "sort");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<SecurityOpen> dictPage = securityOpenRepository.findAll((root, query, builder) -> {
        	List<Predicate> predicates = new ArrayList<>();
        	if (securityOpen != null) {
        		if (securityOpen.getId()!=null) {
	                predicates.add(builder.equal(root.get("id"), securityOpen.getId()));
	            }
        		if (securityOpen.getIsShow()!=0) {
	                predicates.add(builder.equal(root.get("isShow"), securityOpen.getIsShow()));
	            }
	            if (StringUtils.isNotEmpty(securityOpen.getTitle())) {
	                predicates.add(builder.like(root.get("title"), "%" + securityOpen.getTitle() + "%"));
	            }
        	}
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<SecurityOpen>(dictPage);
    }
}